import './env';


import express from 'express';
import log from './log';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import session from 'express-session';
import connectRedis from 'connect-redis';
import sessionConfig from './config/session-config';
import index from './routes/index';

const RedisStore = connectRedis(session);
const app = express();

app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: false }));
app.use(cookieParser(process.env.APP_COOKIE_KEY));

app.use(
  session({
    store: new RedisStore(sessionConfig.redis),
    secret: sessionConfig.secret,
    key: sessionConfig.key,
    cookie: sessionConfig.cookie,
    resave: true,
    rolling: true,
    saveUninitialized: false
  })
);
// logger
app.post('*', async (req, res, next) => {
  //响应开始时间
  const start = new Date();
  try {
    //开始进入到下一个中间件
    await next();
    //记录响应日志
    log.i(req, res, new Date() - start);
  } catch (error) {
    //记录异常日志
    log.e(req, error, new Date() - start);
  }
});

app.use('/', index);
export default app;